class JsSoundFxTagLib {

    static namespace = "jsfx"
  
    def jsDir = createLinkTo(dir:pluginContextPath,file:'js')

    def final DEFAULT_LIBRARY_FILENAME = 'audioSampleLibrary'
    def final DEFAULT_COLLECTION_NAME = 'defaultAudioSamples'

    def includes = { attrs ->

        out << """
            <script type='text/javascript' src='${jsDir}/audio.js'></script>
            <script type='text/javascript' src='${jsDir}/jsfx.js'></script>
            <script type='text/javascript' src='${jsDir}/jsfxlib.js'></script>"""
            out << loadLibrary(attrs.library)

            out << """ <script type='text/javascript'>
                var jsfxWaves={}
                ${loadCollection(attrs.collection)}
            </script>
        """
     
    }

    def loadCollection = {attrs ->
        out << "<script>"
        out << loadCollection(attrs.collection)
        out << "</script>"
    }

    private def loadLibrary(libraryFile){
        return """<script type='text/javascript' src='js/${libraryFile ?: DEFAULT_LIBRARY_FILENAME }.js'></script>"""
    }

    private def loadCollection(collectionName){
        return  "jsfxWaves.${collectionName?:DEFAULT_COLLECTION_NAME} = jsfxlib.createWaves(${collectionName?:DEFAULT_COLLECTION_NAME})"
    }    

    def play = {attrs ->        
        out << """<script>jsfxWaves.${attrs.collection?:DEFAULT_COLLECTION_NAME}.${attrs.sound}.play();</script>"""
    }


    def createLink = { attrs,body ->
        def event = attrs.event ? attrs.event : 'onclick';    
        out << """
       <a href='${g.createLink(attrs)}' ${event}='jsfxWaves.${attrs.collection?:DEFAULT_COLLECTION_NAME}.${attrs.sound}.play(); return false;'>
            ${body.call()}
        </a> """
    }

   def soundZone = { attrs,body ->
       def event = attrs.event ? attrs.event : 'onmouseover';
       def soundEvent = """  ${event}='jsfxWaves.${attrs.collection?:DEFAULT_COLLECTION_NAME}.${attrs.sound}.play(); return false;'"""


       def final TAG_OPEN_REGEX = "<[^/].[^>]*>"
       def firstTag = body.call().toString().find(TAG_OPEN_REGEX)
       def firstTagWithSound = firstTag.replace('>',soundEvent+'>')
       out << body.call().replace(firstTag,firstTagWithSound)

    }

}